/**
 * Created by Aimee on 14-11-10.
 */
define(['jquery', 'jquerymobile', 'net', 'dialogs', 'activity_details', 'activity_register'], function($, m, net, dia, activityDetail, activityRegister) {
    // Nick added for pull to refresh start
    var isScrolling = false,
        iScroll_activity = {
        myScroll: null,
        allowGetMore: true,
        pullDownAction: function() {
            getActivities(true);
        },
        pullUpAction: function() {
            getActivities();
        },
        loaded: function(wrapper) {
            var $wrapper = $("#" + wrapper),
                $pullDownEl = $wrapper.find("#pullDown"),
                $pullDownLabel = $pullDownEl.find(".pullDownLabel"),
                pullDownOffset = $pullDownEl[0].offsetHeight,
                $pullUpEl = $wrapper.find("#pullUp"),
                $pullUpLabel = $pullUpEl.find(".pullUpLabel"),
                $pullUpIcon = $pullUpEl.find(".pullUpIcon"),
                pullUpOffset = $pullUpEl[0].offsetHeight;

            iScroll_activity.myScroll = new iScroll(wrapper, {
                hScrollbar: false,
                vScrollbar: false,
                useTransition: true,
                topOffset: pullDownOffset,
                onRefresh: function () {
                    if ($pullDownEl.hasClass("loading")) {
                        $pullDownEl.removeClass("loading");
                        $pullDownLabel.text("Pull down to refresh...");
                    } else if ($pullUpEl.hasClass("loading")) {
                        $pullUpEl.removeClass("loading");
                        if (iScroll_activity.allowGetMore) {
                            $pullUpIcon.show();
                            $pullUpLabel.text("Pull up to load more...");
                        } else {
                            $pullUpIcon.hide();
                            $pullUpLabel.text("No more articles available!");
                        }
                    }
                },
                onScrollMove: function () {
                    if (this.y > 5 && !$pullDownEl.hasClass("flip")) {
                        $pullDownEl.addClass("flip");
                        $pullDownLabel.text("Release to refresh...");
                        this.minScrollY = 0;
                    } else if (this.y < 5 && $pullDownEl.hasClass("flip")) {
                        $pullDownEl.removeClass("flip");
                        $pullDownLabel.text("Pull down to refresh...");
                        this.minScrollY = -pullDownOffset;
                    } else if (this.y < (this.maxScrollY - 5) && !$pullUpEl.hasClass("flip")) {
                        if (iScroll_activity.allowGetMore) {
                            $pullUpEl.addClass("flip");
                            $pullUpLabel.text("Release to refresh...");
                            this.maxScrollY = this.maxScrollY;
                        }
                    } else if (this.y > (this.maxScrollY + 5) && $pullUpEl.hasClass("flip")) {
                        if (iScroll_activity.allowGetMore) {
                            $pullUpEl.removeClass("flip");
                            $pullUpLabel.text("Pull up to load more...");
                            this.maxScrollY = pullUpOffset;
                        }
                    }
                    isScrolling = true;
                },
                onScrollEnd: function () {
                    if ($pullDownEl.hasClass("flip")) {
                        $pullDownEl.attr("class", "loading");
                        $pullDownLabel.text("Loading...");
                        iScroll_activity.pullDownAction();
                    } else if ($pullUpEl.hasClass("flip")) {
                        if (iScroll_activity.allowGetMore) {
							iScroll_activity.allowGetMore = false;
                            $pullUpEl.attr("class", "loading");
                            $pullUpLabel.text("Loading...");
                            iScroll_activity.pullUpAction();
                        }
                    }
                    setTimeout(function() {
                        isScrolling = false;
                    }, 500);
                }
            });
        }
    };
    // Nick added for pull to refresh end
    //当前页码
    var currentPageNumber = 1;

    // 上一次滚动的位置
    var scrollTopBefore = 0;

    // 控制底部事件激发开关 0表示开 非0表示关闭时间
    var scrollButtomOn = 0;

    //查询到的活动数据
    var v_activities = [];

    // 补充0
    function pad(n, width, z) {
        z = z || '0';
        n = n + '';
        return n.length >= width ? n : new Array(width - n.length + 1).join(z) + n;
    }

    function getMonthString(month) {
        month = month + 1;
        if (month == 1)
            return 'Jan';
        else if (month == 2)
            return 'Feb';
        else if (month == 3)
            return 'Mar';
        else if (month == 4)
            return 'Apr';
        else if (month == 5)
            return 'May';
        else if (month == 6)
            return 'June';
        else if (month == 7)
            return 'July';
        else if (month == 8)
            return 'Aug';
        else if (month == 9)
            return 'Sept';
        else if (month == 10)
            return 'Oct';
        else if (month == 11)
            return 'Nov';
        else if (month == 12)
            return 'Dec';
        else {
            console.assert(false, '月份 %o 不存在 ', month );
        }
    }

    /**
     * 展示过滤按钮样子
     */
    function displayFilter() {
        if ((!$.isEmptyObject(localStorage['activity_selected_tags'])) &&
            (localStorage['activity_selected_tags'].toString().split(',').length < 9)) {
            $('#activities_btn_filter').removeClass('filter').addClass('filterOn');
        } else {
            $('#activities_btn_filter').removeClass('filterOn').addClass('filter');
        }

    }

    /**
     * 禁用滚动时间3秒
     */
    function disableScrollBottom() {
        scrollButtomOn = 3;
        var timer = setInterval(function() {
            if (scrollButtomOn == 0) {
                clearInterval(timer);
                return;
            }
            scrollButtomOn--;
        }, 1000);
    }

    $('#activities_btn_menu').on('click', function(evt) {
        $('.ui-panel-inner').css({'padding':'0px'});
        $('.push_nees_opacity').css('min-height',$(window).height());
        $('#activities_content').css('max-height',$(window).height()-40);
        $('#activities_panel_menu').css('min-height',$(window).height());
        $('#activities_push_ul').css('min-height',$(window).height());
        $('#activities_auto_height').css('min-height',$(window).height()-354);
        console.log($('#activities_panel_menu').css('min-height'));
        console.log($('#activities_push_ul').css('min-height'));
        console.log($('#activities_auto_height').css('height'));
        var username = localStorage['username'] + '!';
        $("#activities_push_username").html(username);
        $( "#activities_panel_menu" ).panel( "open" );

    });

    //获取活动
    // Nick removed for pull to refresh start
    // function getAcvtivities() {
    // Nick removed for pull to refresh end
    // Nick added for pull to refresh start
    function getActivities(refresh) {
        if (refresh) {
            currentPageNumber = 1;
            v_activities = [];
        }
    // Nick added for pull to refresh end
        var postDate = {};
        postDate['pager.pageNo'] = currentPageNumber;
        postDate['pager.pageSize'] = 5;
//        postDate['keyWord'] = null;
        if ((!$.isEmptyObject(localStorage['activity_selected_tags'])) &&
            (localStorage['activity_selected_tags'].toString().split(',').length > 0) &&
            (localStorage['activity_selected_tags'].toString().split(',').length < 9)) {
            postDate['tagNames'] = localStorage['activity_selected_tags'].toString().substr(0, (localStorage['activity_selected_tags'].length - 1));
        }

        net.post('activity/show', postDate, function(error) {

        }, function(response) {
            console.log('activity %o', response.data);
            if(response.code != 0) {

            } else {
                // Nick removed for pull to refresh start
                // if(response.data.activity.length < 1) {
                //     var li = '\<li style="text-align: center;font-weight: normal;font-size: 14px;color: #404040;background-color: rgba(0,0,0,0);border: none;text-shadow: none;">No more articles available!</li>';
                //     $('#activities_listview_news').append(li);
                //     $('#activities_listview_news').listview( "refresh" );
                //     $('#activities_content').off('scroll');
                // } else {
                //     v_activities = v_activities.concat(response.data.activity);
                //     console.log(' 查询到的所有活动 %o', v_activities);

                //     $.each(response.data.activity, function(index,value) {
                // Nick removed for pull to refresh end
                // Nick added for pull to refresh start
                var activityList = response.data.activity,
                    activityListLength = activityList.length,
                    activityHTML = "",
                    activityArray = [],
                    $activities_listview = $("#activities_listview_news");
                if (activityListLength > 0) {
                    v_activities = v_activities.concat(activityList);
                    $.each(activityList, function(index,value) {
                // Nick added for pull to refresh end
                        var startDate = new Date(value.startTime * 1000);
                        var endDate = new Date(value.endTime * 1000);
                        var startTime = 'Start: ' + pad(startDate.getHours(), 2) + ':' + pad(startDate.getMinutes(),2) + ', ' + startDate.getDate() + " " + getMonthString(startDate.getMonth()) + " " + startDate.getFullYear();
                        var endTime = 'End: ' + pad(endDate.getHours(),2) + ':' + pad(endDate.getMinutes(),2) + ', ' + endDate.getDate() + " " + getMonthString(endDate.getMonth()) + " " + endDate.getFullYear();
                        var venue = 'Venue: ' + value.venue;
                        var li = creatActivity(value.banner, value.subject, value.briefContent,startTime ,endTime , venue, value.tags);
                        // Nick removed for pull to refresh start
                        // $('#activities_listview_news').append(li);
                        // $('#activities_listview_news').listview("refresh");
                        // Nick removed for pull to refresh end
                        // Nick added for pull to refresh start
                        activityArray.push(li);
                        // Nick added for pull to refresh end
                    });
                    currentPageNumber++;
                    // Nick added for pull to refresh start
                    activityHTML = activityArray.join("");
                    if (refresh) {
                        $activities_listview.html(activityHTML);
                    } else {
                        $activities_listview.append(activityHTML);
                    }
                    $activities_listview.listview("refresh");
                    if (iScroll_activity.myScroll == null) {
                        iScroll_activity.loaded("activities_wrapper");
                    }
                    // Nick added for pull to refresh end
                }else{
					if(refresh){
						$activities_listview.html("");
					}else{
						$activities_listview.append("");
					}
				}
                // Nick added for pull to refresh start
                var $activities_wrapper = $("#activities_wrapper"),
                    $pullDownEl = $activities_wrapper.find("#pullDown"),
                    $pullUpEl = $activities_wrapper.find("#pullUp"),
                    $pullUpLabel = $pullUpEl.find(".pullUpLabel"),
                    $pullUpIcon = $pullUpEl.find(".pullUpIcon");
                if (refresh) {
					if(activityListLength == 1){
						$pullUpIcon.hide();
						$pullUpEl.show();
                        $pullUpLabel.text("No more articles available!");
					}else if(activityListLength == 0){
						$pullUpIcon.hide();
						$pullUpEl.hide();
					}else{
						$pullUpLabel.text("Pull up to load more...");
						$pullUpIcon.show();
						$pullUpEl.show();
					}
                    if (iScroll_activity.myScroll && iScroll_activity.myScroll.y !== 0) {
                        iScroll_activity.myScroll.y = 0;
                    }
                }
                if (activityListLength < 1) {
                    iScroll_activity.allowGetMore = false;
                } else {
                    iScroll_activity.allowGetMore = true;
                }
                setTimeout(function() {
                    iScroll_activity.myScroll.refresh();
					if(activityListLength == 0){
						$pullUpEl.show();
						$pullUpIcon.hide();
                        $pullUpLabel.text("No more articles available!");						
					}
                    disableClickEvent(false);
                }, 800);
                window.shouldPageRefresh.newsroom = true;
                window.shouldPageRefresh.activities = false;
                // Nick added for pull to refresh end
            }
        });
    }

    //创建活动
    function creatActivity(banner, subject, brifContent, time, day, venue, tags) {
        console.assert(subject != null, '活动标题 %o 不能为空', subject);
        console.assert(brifContent != null, '活动简介 %o 不能为空', brifContent);
        console.assert(time != null, '活动时间 %o 不能为空', time);
        console.assert(day != null, '活动日期 %o 不能为空', day);
        console.assert(venue != null, '活动地点 %o 不能为空', venue);
        console.assert(tags != null, '活动标签 %o 不能为空', tags);
        var activityBrifContent = brifContent;
        //超过160的字符就显示...
        if (activityBrifContent.length > 160) {
            activityBrifContent = brifContent.substring(0, 160) + '...';
        }

        var html_tags = '';
        if(tags != null) {
            $.each(tags, function(index, val) {
                if (val.name == 'Communications')
                    html_tags += '\<span class="spanTag" style="background-color: rgb(77, 134, 176);">COMM</span>  ';
                if (val.name == 'Corporate Sustainability')
                    html_tags += '\<span class="spanTag" style="background-color: rgb(137, 217, 78);">CS</span>  ';
                if (val.name == 'Finance')
                    html_tags += '\<span class="spanTag" style="background-color: rgb(219, 218, 0);">FIN</span>  ';
                if (val.name == 'Trade Union')
                    html_tags += '\<span class="spanTag" style="background-color: rgb(147, 182, 164);">GTU</span>  ';
                if (val.name == 'Human Resources')
                    html_tags += '\<span class="spanTag" style="background-color: rgb(230, 170, 0);">HR</span>  ';
                if (val.name == 'Innovation')
                    html_tags += '\<span class="spanTag" style="background-color: rgb(76, 176, 170);">INNO</span>  ';
                if (val.name == 'Center Operations')
                    html_tags += '\<span class="spanTag" style="background-color: rgb(138, 116, 122);">OPS</span>  ';
                if (val.name == 'Technical Development')
                    html_tags += '\<span class="spanTag" style="background-color: rgb(121, 110, 172);">TD</span>  ';
            });
        }

        var html = '\<li style="border: 0px;padding: 0px;margin-bottom:10px">\
            <div id="detail_sele">\
                <div style="width: 100%" >\
                    <img src="'+banner+'"\ style="width: 100%" alt=""/>\
                </div>\
                <label style="margin: 10px; font-size: 18px; white-space:normal;color: #404040">'+ subject +'\</label>\
                <div style="margin: 10px">\
                    <div style="white-space:normal;font-weight: normal;font-size: 12px;color: #404040">'+ activityBrifContent.replace(/\n/g,'</br>') +'\</div>\
                </div>\
                <div style="margin: 10px;font-size: 11px;color: #404040;">\
                    <span style="display: block;white-space: normal;">'+ time +'\</span>\
                    <span style="display: block;white-space: normal;">'+ day +'\</span>\
                    <span style="display: block;white-space: normal;">'+ venue +'\</span>\
                </div>\
                <div style="margin: 10px;width: auto;white-space: normal;">\
                    '+ html_tags +'\
                \</div>\
                <div style="border-bottom: solid 1px;border-bottom-color: #C0C0C0;width: 100%;clear:left;padding-top:10px;"></div>\
            </div>\
            <div id="activity_nowRegister" style="margin: 10px 0px 10px 10px;width: auto;height: 28px;line-height: 28px;">\
                <ul style="padding: 0px;list-style: none;">\
                    <li style="width: 90%;float: left;font-size: 14px;font-weight: normal;">Register now</li>\
                    <li class="right_chevron" style="width: 10%;float: right;height: 28px;line-height: 28px;"></li>\
                </ul>\
            </div>\
            </li>';
        return html;
    }

    // 点击某一个活动
    $('#activities_listview_news').off('click')
        .on('click', '#detail_sele', function(evt) {
            // Nick disable click event for scrolling start
            if (isScrolling) return false;
            // Nick disable click event for scrolling end
            console.log('当前活动的index %o', $(this).parent().index());
            activityDetail.showDetailWithActivity(v_activities[$(this).parent().index()]);
            activityDetail.from('#activities');
            console.log('当前选中的活动 %o', v_activities[$(this).parent().index()]);
            $.mobile.newChangePage("#activity_detail",{ transition: "slide",reverse: false,changeHash: false});
        }).on('click', '#activity_nowRegister', function(evt) {
            /*console.log('当前活动的index %o', $(this).parent().index());
            console.log('当前选中的活动 %o', v_activities[$(this).parent().index()]);
            activityRegister.setAcvtivities(v_activities[$(this).parent().index()]);
            activityRegister.from('#activities');
            $.mobile.newChangePage('#activityRegister',{ transition: "slide",reverse: false, changeHash:false});*/
            // Nick disable click event for scrolling start
            if (isScrolling) return false;
            // Nick disable click event for scrolling end
            console.log('当前活动的index %o', $(this).parent().index());
            var _activity = v_activities[$(this).parent().index()]; 
            console.log('当前选中的活动 %o',_activity);
            var _activityFlag = _activity['flag'];
            if(!_activityFlag){
                activityRegister.setAcvtivities(_activity);
                activityRegister.from('#activities');
                $.mobile.newChangePage('#activityRegister',{ transition: "slide",reverse: false, changeHash:false});
            }else{
                if(_activityFlag=='activity.deadTime'){
                    dia.alert("Oops!","You are too late! The registration of the activity is already closed.", ['OK'], function () {
                             return false;
                     });
                }else if(_activityFlag=='activity.limitNum'){
                    dia.alert("Oops!","Sorry but your registration cannot be processed now as the activity has reached its maximum capacity.", ['OK'], function () {
                             return false;
                     });
                }else if(_activityFlag=='activity.appIsTwo'){
                    dia.alert("Oops!","Looks like you have already registered this activity!", ['OK'], function () {
                         return false;
                     });
                }else{
                    dia.alert("Oops!","Looks like have other issues. please contact #red help center!", ['OK'], function () {
                         return false;
                     });
                }
            }
        });




    // 点击新闻项，菜单隐藏
    $('#activities_push_newsroom').on('click', function(evt) {
        // Nick added for pull to refresh start
        initPageLoading("news_wrapper");
        // Nick added for pull to refresh end
        $.mobile.newChangePage("#newsroom",{ transition: "slide",reverse: false,changeHash: false});
    });

    // 点击注销，返回登录
    $('#activities_push_logon').on('click', function(evt) {
        $.mobile.newChangePage('#logon',{transition: "slide",reverse: true,changeHash: false});

        //注销用户后复选框清空
        $('#all_check').removeClass('sel').addClass('nor');
        $('div[name="sbox"]').each(function(index, val) {
            $(val).removeClass('sel').addClass('nor');
        });
        // Nick added for pull to refresh start
        cleanUpListItems();
        $(".wrapper").find("#pullUp").hide();
        window.shouldPageRefresh.newsroom = true;
        window.shouldPageRefresh.activities = true;
        // Nick added for pull to refresh end
    });

    //推出activities 页面
    $('#activities_push_activities').on('click', function(evt) {
        $( "#activities_panel_menu" ).panel( "close" );
    });
    
    $('#activities_push_AR').on('click', function(evt) {
        cordova.exec(function(){cordova.logger.debug("success");}, function(){cordova.logger.debug("error");}, "ShowVideoPlaybackView", "showVideoPlaybackView", []);
    });

    $('#activities_push_Laisee').on('click', function(evt) {
        //Green Laisee entrance
        var cuser = null;
        if (localStorage.getItem('login_user')!=null) {
            cuser = JSON.parse(localStorage.getItem('login_user'));
        } else {
            console.assert(false, '还没登录，没有用户信息可填写');
        }
        cordova.exec(function(){console.log("success")}, function(){console.log("error")}, "OpenGreenLaisee", "openGreenLaisee", [JSON.stringify({"account": ""+cuser.staffId+"", "fullName": ""+cuser.english_name+"", "secureToken": "", "location": "CN"})]);
    });

    //推出setting页面
    $('#activities_push_setting').on('click', function(evt) {
        $.mobile.newChangePage("#setting",{ transition: "slide",reverse: false,changeHash: false});
    });

    //推出Filter页面
    $('#activities_btn_filter').on('click',function() {
        $.mobile.newChangePage("#activity_filter",{ transition: "slide",reverse: false,changeHash: false});
    });

    //

    $('#activities').on('pageshow', function(event) {
        console.log('activities show...');
        // Nick removed for pull to refresh start
        // currentPageNumber = 1;
        // Nick removed for pull to refresh end
        // Nick added for pull to refresh start
        disableClickEvent(true);
        // Nick added for pull to refresh end

		window.setBodyOverflow($(document.body));
        $('#activities_content').css('height',($(window).height()-40));

        displayFilter();

        //显示之前清除数据
        // Nick removed for pull to refresh start
        // $('#activities_listview_news').empty();
        // v_activities = [];
        // getAcvtivities();
        // Nick removed for pull to refresh end
        // Nick added for pull to refresh start
        if (window.shouldPageRefresh.activities) {
            getActivities(true);
        }
        // Nick added for pull to refresh end

        //页面滚动到底部自动加载活动
        // Nick removed for pull to refresh start
        // $('#activities_content').on('scroll', function() {
        //     if ((($(this).scrollTop() + $(this).height()) >= ($(this).children(':first-child').height() - 20)
        //         || ($(this).scrollTop() + $(this).height()) >= ($(this).children(':first-child').height() + 20))
        //         && scrollButtomOn == 0
        //         && $(this).scrollTop() - scrollTopBefore > 0) {
        //         // 禁用开关3秒钟
        //         disableScrollBottom();
        //         console.log('bottom');
        //         getAcvtivities();
        //     }
        //     scrollTopBefore = $(this).scrollTop();
        // });
        // Nick removed for pull to refresh end
        
        window.historyView = [];
    });

    // 消失的时候删除活动
    // Nick removed for pull to refresh start
    // $("#activities").on( "pagehide", function( event ) {
    //     $('#activities_listview_news').empty();
    //     $('#activities_content').off('scroll');
    // });
    // Nick removed for pull to refresh end

    // Nick added for pull to refresh start
    function cleanUpListItems() {
        $("#newsroom_listview_news").empty();
        $("#activities_listview_news").empty();
    }

    function stopEventPropagation(event) {
        event.stopPropagation();
    }

    function initPageLoading(wrapper) {
        var $wrapper = $("#" + wrapper),
            $pullDownEl = $wrapper.find("#pullDown"),
            $pullDownLabel = $pullDownEl.find(".pullDownLabel");

        if ($wrapper.find("ul").html()) {
            $wrapper.find(".scroller").css(window.getVendorStyle("transform"), "translate(0, 0)");
            $pullDownEl.attr("class", "loading");
            $pullDownLabel.text("Loading...");
        }
    }

    function disableClickEvent(addListener) {
        var $disabledBody = $("body.disabled");
        if ($disabledBody.length > 0) {
            if (addListener) {
                $disabledBody[0].addEventListener("click", stopEventPropagation, true);
            } else {
                $disabledBody[0].removeEventListener("click", stopEventPropagation, true);
                $disabledBody.removeClass("disabled");
            }
        }
    }
    // Nick added for pull to refresh end
});